package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"private-domain-overseas-service/app/business/api/internal/config"
	"private-domain-overseas-service/app/business/api/internal/handler"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/timed"

	"github.com/robfig/cron/v3"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	server := rest.MustNewServer(c.RestConf, unAuthHandle(), corsHandle())

	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	svcCtx := svc.NewServiceContext(c)
	contCtx := context.Background()

	t := cron.New()
	timed.RegisterCronJobs(t, contCtx, svcCtx)
	t.Start()
	defer t.Stop()

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

func unAuthHandle() rest.RunOption {
	return rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
		// TODO 自定义处理返回

	})
}

func corsHandle() rest.RunOption {
	return rest.WithCustomCors(func(header http.Header) {
		header.Set("Access-Control-Allow-Headers", "Content-Type, Origin, X-CSRF-Token, Authorization, AccessToken, Token, Range, traceId")
	}, nil)
}
